package com.qt.socket.tcpwork.work4;

import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @Author zsf
 * @Date 2023/10/5 22:53
 * @Version 1.0
 */
public class MyRunable  implements Runnable{

    private Socket socket;

    public MyRunable(Socket socket){
        this.socket = socket;
    }


    @Override
    public void run() {

        try {
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

            String name = UUID.randomUUID().toString().replaceAll("-", "");
            //写入文件
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("bbb\\" + name + ".txt"));

            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                bos.write(bytes, 0, len);
            }
            bos.close();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(socket != null){
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
